package com.codez.unionpay.netty;

import java.util.Scanner;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author zhengdechao
 * @createTime : 2019-05-20
 *
 */

public class LocalClientHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("active ... ???????");
		ctx.writeAndFlush(Unpooled.copiedBuffer("hello server", CharsetUtil.UTF_8));
//		Scanner scanner = new Scanner(System.in);
//		while(true) {
//			System.out.print("请输入:");
//			String m = scanner.nextLine();
//			ctx.writeAndFlush(Unpooled.copiedBuffer(m,CharsetUtil.UTF_8));
//			if("e".equals(m)) {
//				break;
//			}
//		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf in = (ByteBuf) msg;
		System.out.println(in.toString(CharsetUtil.UTF_8));
//		Thread.sleep(5000);
//		ctx.disconnect();
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// 每次读完都可以给服务器发送消息
		Scanner scanner = new Scanner(System.in);
		System.out.print("请输入:");
		String m = scanner.nextLine();
		ctx.writeAndFlush(Unpooled.copiedBuffer(m,CharsetUtil.UTF_8));
		if("baibai".equals(m)) {
			ctx.disconnect();
		}
		super.channelReadComplete(ctx);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
	
}
